package cn.edu.seu.herald.informationplatform.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import cn.edu.seu.herald.informationplatform.bean.league.Picture;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.PictureDao;
import cn.edu.seu.herald.informationplatform.util.filetools.PicTools;

public class PictureUpload extends HttpServlet {  

	@Override
	public void init() throws ServletException {	
	}
	
	@Override
	public void doPost(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		try {
			  
			  request.setCharacterEncoding("utf-8");
			  response.setCharacterEncoding("utf-8");
			  response.setContentType("text/html;charset=utf-8");
			  int albumId = -1;
			  LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
			  boolean isMultipart = ServletFileUpload.isMultipartContent(
			  request);
			  if (!isMultipart) {
			  System.out.println("File Not Uploaded");
			  } else {
			  FileItemFactory factory = new DiskFileItemFactory();
			  ServletFileUpload upload = new ServletFileUpload(factory);
			  upload.setHeaderEncoding(request.getCharacterEncoding());
			  List<?> items = null;
			  try {
			  items = upload.parseRequest(request);
			  System.out.println("items: "+items);
			  } catch (FileUploadException e) {
			  e.printStackTrace();
			  }
			  Iterator<?> itr = items.iterator();
			  
			  while (itr.hasNext()) {		    
			  FileItem item = (FileItem) itr.next();
				  if(item.getFieldName().equals("albumId"))albumId = Integer.parseInt(item.getString());
				 
				  if(item.getFieldName().equals("picName")){
					  Picture picture = new Picture();
					  picture.setName(item.getString(request.getCharacterEncoding()));
					 
				  if(itr.hasNext()){  
					  FileItem itemPic = (FileItem) itr.next();
					  if (!itemPic.isFormField()){
						  if(itemPic.getName()!=null&&itemPic.getName()!="")
						  {
						  System.out.println("HERE");
						  String itemName = FilenameUtils.getName(itemPic.getName());
						  
						  Random generator = new Random();
						  int r = Math.abs(generator.nextInt());

						  String reg = "[.*]";
						  String replacingtext = "";
						  
						  Pattern pattern = Pattern.compile(reg);
						  Matcher matcher = pattern.matcher(itemName);
						  StringBuffer buffer = new StringBuffer();

						  while (matcher.find()) {
						  matcher.appendReplacement(buffer, replacingtext);
						  }
						  int IndexOf = itemName.indexOf("."); 
						  String preFileName = itemName.substring(IndexOf);
						  /*System.out.println("preFileName: "+preFileName);
			              System.out.println("fileName:" + buffer.toString());
			              System.out.println("fileType:" + item.getContentType());
			              System.out.println("fileSize:" + item.getSize() + "byte");*/
						  String finalimage = buffer.toString()+"_"+r+preFileName;
						  System.out.println("Final Image==="+finalimage);
						  String path = getServletContext().getRealPath("/");
						  Properties pro = System.getProperties();
					         String osName = pro.getProperty("os.name");
					         File saveFile = null;
					         String savePath = null;
					         String relativeSavePath = null;
					         if("Linux".equals(osName) || "linux".equals(osName) || "LINUX".equals(osName)){
					        	 savePath = path+"/pictures/"+finalimage;
					        	 
					        	 saveFile = new File(savePath); 
					         }
					         else{
					        	 savePath = path+"pictures\\"+finalimage;
					        	 saveFile = new File(savePath);
					         }
					         relativeSavePath = "pictures/"+finalimage;
						  itemPic.write(saveFile);
						  PicTools.correctPicSize(savePath);
						  picture.setAddress(relativeSavePath);
						 
						  picture.setLeagueId(luSessionCookieAccess.getLeagueId());
						  picture.setAlbumId(albumId);
						  
						  PictureDao pictureDao =PictureDao.getDao();
						  pictureDao.addPicture(picture);
						  
					  }
				  }
				  }
			  /*String name = item.getFieldName();
			  System.out.println("name: "+name);
			  String value = item.getString();
			  System.out.println("value: "+value);*/
			  }
			  }
			  }	
			  response.sendRedirect("./album.jsp?league="+luSessionCookieAccess.getLeagueId()+"&album="+albumId); 
		}
	    catch (Exception e) {
	    	e.printStackTrace();
	    }
	}
}
